package cn.com.tarotframework.config;



import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class ThreadPoolTaskExecuteConfig {


    @Bean("node-flow-pool-0")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //获取cpu核心数
        int cpu = Runtime.getRuntime().availableProcessors();
        //核心线程数目
        executor.setCorePoolSize(cpu * 2);
        //指定最大线程数
        executor.setMaxPoolSize(cpu * 2);
        //队列中最大的数目
        executor.setQueueCapacity(cpu * 2 * 10);
        // 设置线程的最大空闲时间
        executor.setKeepAliveSeconds(60);
        // 设置线程名字的前缀
        executor.setThreadNamePrefix("node-flow-pool-0-");
        // 设置拒绝策略：当线程池达到最大线程数时，如何处理新任务
        // CALLER_RUNS：在添加到线程池失败时会由主线程自己来执行这个任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 线程池初始化
        executor.initialize();
        return executor;
    }


    /**
     * 动态创建线程池
     * @param poolName 自定义线程名称
     * @param taskSize 任务数 （任务数越多，则线程池分配的线程就越少）
     * @return ThreadPoolTaskExecutor
     */
    public static ThreadPoolTaskExecutor trendsCreateThreadPoll(String poolName, int taskSize){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //获取cpu核心数
        int cpu = Runtime.getRuntime().availableProcessors();
        //核心线程数目
        executor.setCorePoolSize(cpu * 2 / taskSize);
        //指定最大线程数
        executor.setMaxPoolSize(cpu * 2 / taskSize);
        //队列中最大的数目
        executor.setQueueCapacity(cpu * 2 * 10 / taskSize);
        // 设置线程的最大空闲时间
        executor.setKeepAliveSeconds(60);
        // 设置线程名字的前缀
        executor.setThreadNamePrefix(poolName+"-");
        // 设置拒绝策略：当线程池达到最大线程数时，如何处理新任务
        // CALLER_RUNS：在添加到线程池失败时会由主线程自己来执行这个任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 线程池初始化
        executor.initialize();
        executor.setThreadNamePrefix(poolName+"-");
        return executor;
    }

}